package com.tusuo.stds.ui.suggest;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.tusuo.stds.R;
import com.tusuo.stds.ui.BaseToolbarActivity;
import com.tusuo.stds.ui.ToolbarOwner;
import com.tusuo.stds.util.Utils;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.ColorRes;

import java.util.ArrayList;

import me.nereo.multi_image_selector.MultiImageSelectorActivity;


@EActivity(R.layout.activity_suggest)
public class SuggestActivity extends BaseToolbarActivity<SuggestView, SuggestPresenter>
        implements SuggestView{

    @ViewById(R.id.tv_banner)
    TextView tvBanner;

    @ViewById(R.id.suggest_et_text)
    EditText etText;
    @ViewById(R.id.suggest_et_address)
    EditText etAddress;

    @ViewById(R.id.suggest_btn_commit)
    Button btnCommit;

    @ViewById(R.id.suggest_tv_text_count)
    TextView tvCount;
    @ViewById(R.id.suggest_tv_pic_count)
    TextView tvPicCount;

    @ViewById(R.id.suggest_iv_image1)
    ImageView ivImage1;
    @ViewById(R.id.suggest_iv_image2)
    ImageView ivImage2;
    @ViewById(R.id.suggest_iv_image3)
    ImageView ivImage3;
    @ViewById(R.id.suggest_iv_image4)
    ImageView ivImage4;

    @ViewById(R.id.suggest_layout_image4)
    RelativeLayout layoutImage4;

    @ColorRes(R.color.white)
    int toolbarBgColor;
    @ColorRes(R.color.black)
    int toolbarTextColor;

    private int textNum = 0;
    private boolean isAnimationOver = true;
    private int currentImage = 1;
    private ArrayList<ImageView> images;
    private ArrayList<String> imagePath;

    @NonNull
    @Override
    public SuggestPresenter createPresenter() {
        return new SuggestPresenter(this);
    }


    @AfterViews
    void initData() {
        setupUI(this, toolbarBgColor, toolbarTextColor);

        ToolbarOwner.Config config = new ToolbarOwner.Config("意见反馈", true, R.drawable.ic_back_dark, null);
        mToolbarOwner.setConfig(config);

        showSlogan();

        etText.setFocusable(true);
        etText.setFocusableInTouchMode(true);

        tvCount.setText("0");
        tvPicCount.setText("0");
        imagePath = new ArrayList<>();

        images = new ArrayList<>();
        images.add(ivImage1);
        images.add(ivImage2);
        images.add(ivImage3);
        images.add(ivImage4);

        etText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                textNum = s.length();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvCount.setText(textNum + "");
                    }
                });
            }
        });
    }

    public void picDetail(View v) {
        switch (v.getId()) {
            case R.id.suggest_iv_image1:
                currentImage = 1;
                break;
            case R.id.suggest_iv_image2:
                currentImage = 2;
                break;
            case R.id.suggest_iv_image3:
                currentImage = 3;
                break;
            case R.id.suggest_iv_image4:
                currentImage = 4;
                break;
        }



        Intent intent = new Intent(this,PictrueDetailActivity.class);
        intent.putStringArrayListExtra("imagePath",imagePath);
        intent.putExtra("currentImage",currentImage);
        startActivityForResult(intent,10024);
    }

    @Click(R.id.suggest_layout_image4)
    public void addPic() {

        Intent intent = new Intent(SuggestActivity.this, MultiImageSelectorActivity.class);
        // 是否显示调用相机拍照
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, false);
        // 最大图片选择数量
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 4 - imagePath.size());
        // 设置模式 (支持 单选/MultiImageSelectorActivity.MODE_SINGLE 或者 多选/MultiImageSelectorActivity.MODE_MULTI)
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);

        startActivityForResult(intent, 10000);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 10024 && requestCode == 10024) {
            //　图片查看的Activity回传数据
            ArrayList<String> imagePath = data.getStringArrayListExtra("imagePath");
            this.imagePath = imagePath;
        }else if (requestCode == 10000) {
            if (data == null) {
                return;
            }
            ArrayList<String> listExtra = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
            if (imagePath.size()==0) {
                imagePath.addAll(listExtra);
            }else {
                for (String str : listExtra) {
                    if (!imagePath.contains(str)) {
                        imagePath.add(str);
                    }
                }
            }
        }
        flushUI();
    }

    private void flushUI() {
        if (imagePath == null) {
            return;
        }

        tvPicCount.setText(imagePath.size() + "");

        switch (imagePath.size()) {
            case 1:
                ivImage1.setVisibility(View.VISIBLE);
                ivImage2.setVisibility(View.GONE);
                ivImage3.setVisibility(View.GONE);
                ivImage4.setVisibility(View.GONE);
                layoutImage4.setVisibility(View.VISIBLE);
                break;
            case 2:
                ivImage1.setVisibility(View.VISIBLE);
                ivImage2.setVisibility(View.VISIBLE);
                ivImage3.setVisibility(View.GONE);
                ivImage4.setVisibility(View.GONE);
                layoutImage4.setVisibility(View.VISIBLE);

                break;
            case 3:
                ivImage1.setVisibility(View.VISIBLE);
                ivImage2.setVisibility(View.VISIBLE);
                ivImage3.setVisibility(View.VISIBLE);
                ivImage4.setVisibility(View.GONE);
                layoutImage4.setVisibility(View.VISIBLE);
                break;
            case 4:
                ivImage1.setVisibility(View.VISIBLE);
                ivImage2.setVisibility(View.VISIBLE);
                ivImage3.setVisibility(View.VISIBLE);
                ivImage4.setVisibility(View.VISIBLE);
                layoutImage4.setVisibility(View.GONE);
                break;
            default:
                ivImage1.setVisibility(View.GONE);
                ivImage2.setVisibility(View.GONE);
                ivImage3.setVisibility(View.GONE);
                ivImage4.setVisibility(View.GONE);
                layoutImage4.setVisibility(View.VISIBLE);
                break;
        }

        for (String path : imagePath) {
            Glide
                    .with(SuggestActivity.this)
                    .load(path)
                    .crossFade()
                    .centerCrop()
                    .into(images.get(imagePath.indexOf(path)));
        }
    }

    @Override
    public void showErrMsg(String text) {
        tvBanner.setText(text);
        tvBanner.setTextColor(Color.RED);
        etText.requestFocus();
    }

    @Override
    public void showSlogan() {
        tvBanner.setText(getString(R.string.slogan));
        tvBanner.setTextColor(Color.WHITE);
    }

    @Click(R.id.suggest_btn_commit)
    public void commitSuggestion() {
        if (textNum < 10) {
            presenter.showErrMsg("您输入的文字少于10个字，请重新输入");
            return;
        }

        String content = etText.getText().toString().trim();
        String contact = "";

        if (TextUtils.isEmpty(etAddress.getText())) {
            contact = etAddress.getText().toString().trim();
        }

        presenter.upLoadImage(imagePath,content,contact);

    }

    @Click(R.id.suggest_btn_join)
    public void clickJoiningQQGroup() {
        if (Utils.App.isQQAppInstalled(this) && joinQQGroup("HPeevQESLkvlytn7DLoRxaIkg4dS3xzH")) {
//            Utils.UI.showToastLong("操作失败！\n请先手动打开手机QQ客户端或版本过低");
        } else {
            Utils.UI.showToastLong("请先安装手机QQ客户端");
        }
    }

    public boolean joinQQGroup(String key) {
        Intent intent = new Intent();
        intent.setData(Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26k%3D" + key));
        // 此Flag可根据具体产品需要自定义，如设置，则在加群界面按返回，返回手Q主界面，不设置，按返回会返回到呼起产品界面
        // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        try {
            startActivity(intent);
            return true;
        } catch (Exception e) {
            // 未安装手Q或安装的版本不支持
            return false;
        }
    }


    public void isCommitSuccess(boolean isSuccess) {
        if (isSuccess) {
            Intent intent = new Intent(SuggestActivity.this,SuggestSuccessActivity.class);
            startActivity(intent);
            finish();
        }else {
            Toast.makeText(this, "提交失败,请重试", Toast.LENGTH_SHORT).show();
        }
    }
}
